<?php

namespace addons\xykeep\listener;

use addons\epay\library\Service;
use app\api\model\xykeep\User;
use app\api\controller\xykeep\Pay;

/**
 * 订单退款监听
 */
class RefundOrder
{
    public function xykeepOrderRefundAfter(&$params)
    {
        $order = $params['order'];
        $orderType = $params['type'];

        list($orderModel, $order_cn) = Pay::getOrderInstance($orderType);

        if($order['pay_type']=='wechat'){
            $refund=[
                'out_trade_no' => $order['order_sn'],
                'out_refund_no' => time(),
                'total_fee' =>  bcmul((string)$order['pay_fee'],'100'),
                'refund_fee' => bcmul((string)$order['pay_fee'],'100'),
                'refund_desc' => $order_cn.'退款',
                'type' => 'miniapp',
            ];
            Service::refunds($refund);
        }else{
            //余额支付
            //更新用户余额
            User::money($order['pay_fee'], $order['user_id'], 'refund', $order_cn.'退款,订单号:'.$order['order_sn'],$order['id']);
        }

        //减少用户累计消费
        $userInfo = User::where(['id'=>$order['user_id']])->find();
        $after_consume = bcsub((string)$userInfo['xykeep_consume'],(string)$order['pay_fee'],2);
        User::where(['id'=>$order['user_id']])->update(['xykeep_consume'=>$after_consume]);


        if(in_array($orderType, ['card','goods','course'])){
            $params = ['order'=>$order,'type'=>$orderType];
            \think\Hook::listen('xykeep_order_back_after', $params);

        }



    }
}